package com.xudow.app.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.activeshare.edu.ucenter.models.course.CourseWithOtherInfo;
import com.activeshare.edu.ucenter.models.order.OrderWithLineitems;
import com.xudow.app.R;
import com.xudow.app.XApplication;
import com.xudow.app.ui.task.CourseDetailTask;
import com.xudow.app.ui.task.OrderDetailTask;
import com.xudow.app.ui.task.PaymentCreateTask;
import com.xudow.app.util.DateUtil;
import com.xudow.app.util.Maps;
import com.xudow.app.util.PriceUtil;

import java.util.HashMap;

/**
 * 订单确认Activity
 *
 * @author lukecheng
 */
public class OrderPreviewActivity extends BaseActivity {
    private final static int DEFAULT_COURSE_HOURS = 10; //默认一对一课时

    private CourseWithOtherInfo course;
    private String orderId; //订单id
    private OrderWithLineitems order;

    private TextView orderSnView, unitPriceView, courseNameView, schoolNameView,
            courseAddressView, courseTimeView, payAmountTextView;

    private RadioButton schoolPayBtn, onlinePayBtn;

    private CourseDetailTask courseDetailTask;
    private OrderDetailTask orderDetailTask;
    private PaymentCreateTask paymentCreateTask;

    private int currentPayMethod;

    private Integer courseHours = null; //课时

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_preview);

        XApplication application = (XApplication) getApplication();
        application.addChainActivity(this);

        orderId = getIntent().getStringExtra("orderId");

        orderSnView = (TextView) findViewById(R.id.order_sn);
        unitPriceView = (TextView) findViewById(R.id.unit_price);
        courseNameView = (TextView) findViewById(R.id.course_name);
        schoolNameView = (TextView) findViewById(R.id.school_name);
        courseAddressView = (TextView) findViewById(R.id.course_address);
        courseTimeView = (TextView) findViewById(R.id.course_time);
        payAmountTextView = (TextView) findViewById(R.id.pay_amount);

        schoolPayBtn = (RadioButton) findViewById(R.id.school_pay);
        onlinePayBtn = (RadioButton) findViewById(R.id.online_pay);

        HashMap<String, String> params = Maps.newHashMap();
        params.put("order_id", orderId);

        showLodingDialog(getString(R.string.loading));

        orderDetailTask = new OrderDetailTask(this, orderDetailHandler);
        addTask(orderDetailTask);
        orderDetailTask.execute(params);
    }

    public void onBackBtnClick(View view) {
        finish();
    }

    /**
     * 支付方式radio选择
     *
     * @param view
     */
    public void onPayOptionSelect(View view) {
        schoolPayBtn.setChecked(false);
        onlinePayBtn.setChecked(false);

        ((RadioButton) view).setChecked(true);

        currentPayMethod = view.getId();
    }

    /**
     * 支付按钮点击
     *
     * @param view
     */
    public void pay(View view) {
        if (R.id.school_pay == currentPayMethod) {
            //到校支付
            showLodingDialog(getString(R.string.processing));

            paymentCreateTask = new PaymentCreateTask(this, paymentCreateTaskHandler);
            addTask(paymentCreateTask);

            if (null == courseHours) {
                courseHours = 1;
            }

            HashMap<String, String> params = Maps.newHashMap();
            params.put("order_id", orderId); //订单编号

            //总价
            float payAmountTmp = course.getActualPrice() * courseHours;
            params.put("pay_amount", "" + payAmountTmp);

            params.put("pay_type", "2"); //'1：网上支付 2：到机构支付

            //现在没有购物车，只有一门课
            params.put("item_ids", "" + order.getItems().get(0).getId());
            params.put("course_hours", "" + courseHours);

            paymentCreateTask.execute(params);
        } else {
            //在线支付
            if (null == courseHours) {
                courseHours = 1;
            }

            Intent intent = new Intent(this, PayActivity.class);
            intent.putExtra("orderId", order.getId());

            //总价
            float payAmountTmp = course.getActualPrice() * courseHours;
            intent.putExtra("orderPrice", PriceUtil.format(payAmountTmp));

            //现在没有购物车，只有一门课
            intent.putExtra("item_ids", "" + order.getItems().get(0).getId());

            if (null == courseHours) {
                courseHours = 1;
            }
            intent.putExtra("course_hours", "" + courseHours);

            startActivity(intent);
        }
    }

    /**
     * 生成支付方式Handler
     */
    private Handler paymentCreateTaskHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideLoadingDialog();

            if (PaymentCreateTask.SUCCESS == msg.what) {
                String message = getString(R.string.school_pay_create_success);
                Toast.makeText(OrderPreviewActivity.this, message, Toast.LENGTH_LONG).show();

                finish();
            } else {
                String message = getString(R.string.process_fail);
                Toast.makeText(OrderPreviewActivity.this, message, Toast.LENGTH_SHORT).show();
            }
        }
    };

    /**
     * 订单详情Handler
     */
    private Handler orderDetailHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideLoadingDialog();

            if (OrderDetailTask.SUCCESS == msg.what) {
                order = (OrderWithLineitems) msg.getData().getSerializable("order");

                //课时
                if (null != order.getItems().get(0).getCourseHour()) {
                    courseHours = order.getItems().get(0).getCourseHour();
                }

                HashMap<String, String> params = Maps.newHashMap();
                params.put("courseid", "" + order.getItems().get(0).getCourseId());

                courseDetailTask = new CourseDetailTask(OrderPreviewActivity.this, courseDetailHandler);
                courseDetailTask.execute(params);
            } else {
                String message = getString(R.string.loading_fail);
                Toast.makeText(OrderPreviewActivity.this, message, Toast.LENGTH_SHORT).show();
            }
        }
    };

    /**
     * 获取课程详情Handler
     */
    private Handler courseDetailHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (CourseDetailTask.SUCCESS == msg.what) {
                course = (CourseWithOtherInfo) msg.getData().getSerializable("course");

                //上课方式字段是：teachingMethod，对应关系1 老师上门   2学生上门  3协商地点
               if (null !=  course.getTeachingMethod()) {
                   switch ( course.getTeachingMethod()) {
                       case 1:
                           findViewById(R.id.course_method_one).setBackgroundColor(getResources().getColor(R.color.dark_rvcode));
                           ((TextView)findViewById(R.id.course_method_one)).setTextColor(getResources().getColor(android.R.color.white));
                           break;
                       case 2:
                           findViewById(R.id.course_method_two).setBackgroundColor(getResources().getColor(R.color.dark_rvcode));
                           ((TextView)findViewById(R.id.course_method_two)).setTextColor(getResources().getColor(android.R.color.white));
                           break;
                       case 3:
                           findViewById(R.id.course_method_three).setBackgroundColor(getResources().getColor(R.color.dark_rvcode));
                           ((TextView)findViewById(R.id.course_method_three)).setTextColor(getResources().getColor(android.R.color.white));
                           break;
                       default:
                           break;
                   }
               }

                orderSnView.setText(order.getOrderSn());
                unitPriceView.setText("￥" + course.getActualPrice());

                courseNameView.setText(course.getName());
                schoolNameView.setText(course.getAgencyName());
                courseAddressView.setText(course.getSchoolAdress());

                if (course.getBeginDate() != null) {
                    String dateStr = DateUtil.dateTimeToStr(course.getBeginDate(), DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI);
                    courseTimeView.setText(dateStr);
                }

                int courseType = course.getType();
                if (2 != courseType) {
                    //非辅导班
                    findViewById(R.id.course_hours_layout).setVisibility(View.VISIBLE);
                    findViewById(R.id.course_hours_layout_border).setVisibility(View.VISIBLE);

                    if (null == courseHours) {
                        courseHours = DEFAULT_COURSE_HOURS;

                        float payAmountTmp = course.getActualPrice() * courseHours;
                        payAmountTextView.setText("￥" + PriceUtil.format(payAmountTmp));
                    } else {
                        payAmountTextView.setText("￥" + order.getTotalPrice());
                    }
                } else {
                    //辅导班

                    //总价就是单价
                    payAmountTextView.setText("￥" + order.getTotalPrice());
                }
            }
        }
    };

    /**
     * 课时选择
     *
     * @param view
     */
    public void onCourseHourClick(View view) {
        TextView courseHourOne = (TextView) findViewById(R.id.course_hours_one);
        TextView courseHourTwo = (TextView) findViewById(R.id.course_hours_two);
        TextView courseHourThree = (TextView) findViewById(R.id.course_hours_three);

        courseHourOne.setTextColor(getResources().getColor(R.color.text_medium));
        courseHourTwo.setTextColor(getResources().getColor(R.color.text_medium));
        courseHourThree.setTextColor(getResources().getColor(R.color.text_medium));

        int colorRed = getResources().getColor(R.color.red);

        switch (view.getId()) {
            case R.id.course_hours_one:
                courseHourOne.setTextColor(colorRed);
                courseHours = 10;
                break;
            case R.id.course_hours_two:
                courseHourTwo.setTextColor(colorRed);
                courseHours = 40;
                break;
            case R.id.course_hours_three:
                courseHourThree.setTextColor(colorRed);
                courseHours = 60;
                break;
            default:
                break;
        }

        float payAmountTmp = course.getActualPrice() * courseHours;
        payAmountTextView.setText("￥" + PriceUtil.format(payAmountTmp));
    }
}
